<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

import { useRouter, useRoute } from 'vue-router'

import LeftOne from '../components/LeftOne.vue'
import AntV_L_1 from '../components/AntV-L-1.vue'
import LeftTwo from '../components/LeftTwo.vue'
import LeftThree from '../components/LeftThree.vue'
import CenterOne from '../components/CenterOne.vue'
import CenterTwo from '../components/CenterTwo.vue'
import RightOne from '../components/RightOne.vue'
import RightTwo from '../components/RightTwo.vue'
import RightThree from '../components/RightThree.vue'

// 导入背景图片
import bg1Image from '../assets/bg1.png'
import bg2Image from '../assets/bg2.png'
import bg3Image from '../assets/bg3.png'
import bg4Image from '../assets/bg4.png'

import { Check, Delete, Edit, Message, Search, Star } from '@element-plus/icons-vue'

// 背景图片数组
const backgroundImages = [
  bg1Image,
  bg2Image,
  bg3Image,
  bg4Image,
  // bg5Image,
  // bg6Image,
  // bg7Image,
  // bg8Image,
  // bg9Image,
  // bg10Image,
  // bg11Image,
  // bg12Image,
  // bg13Image,
  // bg14Image,
  // bg15Image,
  // bg16Image,
  // bg17Image,
  // bg18Image,
  // bg19Image,
  // bg20Image,
  // bg21Image,
  // bg22Image,
  // bg23Image,
  // bg24Image,
  // bg25Image,
  // bg26Image
]

// 当前背景索引 (0 = bg1, 1 = bg2, 2 = 隐藏)
const currentBackgroundIndex = ref(backgroundImages.length)

// 背景图片的 opacity 值
const backgroundOpacityMin = 0.01
const backgroundOpacityMax = 0.8
const backgroundOpacity = ref(backgroundOpacityMin)

// 用于存储 opacity 动画的定时器
let opacityAnimationTimer = null

// 切换背景图片
function toggleBackground() {
  console.log('切换背景')
  console.log(`backgroundOpacity.value = ${backgroundOpacity.value}`)

  let timeout = 0

  // 判断是否正在显示背景图片
  if (currentBackgroundIndex.value !== backgroundImages.length) {
    // 先隐藏背景图片
    animateOpacity('hidden')
    timeout = 2000
  } else {
    // 显示背景图片
    backgroundOpacity.value = backgroundOpacityMin
  }

  // 3秒后切换背景图片
  setTimeout(() => {
    // 轮换背景：bg1 -> bg2 -> 隐藏 -> bg1...
    currentBackgroundIndex.value =
      (currentBackgroundIndex.value + 1) % (backgroundImages.length + 1)
    // 开始 opacity 动画
    animateOpacity('visible')
  }, timeout)
}

// opacity 动画函数
function animateOpacity(visibilityState) {
  // 如果正在执行 opacity 动画，先清除定时器
  if (opacityAnimationTimer) {
    clearInterval(opacityAnimationTimer)
  }

  // let opacity = 0.01
  const interval = 0.01 // 每次增加的值
  const duration = 3000 // 总时间 3 秒
  const steps = duration / (interval * 1000) // 步数
  const stepTime = duration / steps // 每步的时间间隔

  opacityAnimationTimer = setInterval(() => {
    if (visibilityState === 'hidden') {
      backgroundOpacity.value -= interval
    } else {
      backgroundOpacity.value += interval
    }

    // backgroundOpacity.value = opacity

    // 如果 opacity 是1或者是0
    if (
      backgroundOpacity.value <= backgroundOpacityMin ||
      backgroundOpacity.value >= backgroundOpacityMax
    ) {
      clearInterval(opacityAnimationTimer)
      opacityAnimationTimer = null
      backgroundOpacity.value = Math.min(
        backgroundOpacityMax,
        Math.max(backgroundOpacityMin, backgroundOpacity.value)
      )
    }
  }, stepTime)
}

// 获取当前背景图片URL
const getCurrentBackgroundImage = () => {
  if (currentBackgroundIndex.value < backgroundImages.length) {
    return `url(${backgroundImages[currentBackgroundIndex.value]})`
  }
  return 'none'
}

// 获取按钮文本
const getButtonText = () => {
  if (currentBackgroundIndex.value < backgroundImages.length) {
    return `背景 ${currentBackgroundIndex.value + 1}/${backgroundImages.length}`
  }
  return '显示背景'
}

const activeIndex = ref('1')
const handleSelect = (key, keyPath) => {
  console.log(key, keyPath)
}

// 在组件中获取路由实例
const route = useRoute()
const router = useRouter()

// 重绘当前页面的函数
const redrawCurrentPage = () => {
  // 获取当前路由路径
  const currentPath = router.currentRoute.value.path
  // 生成时间戳作为查询参数，确保路由变化
  const timestamp = new Date().getTime()

  router.replace({
    path: currentPath,
    query: {
      ...router.currentRoute.value.query,
      t: timestamp
    }
  })
}

function hardReload() {
  // 获取路由实例和当前路由对象
  const router = useRouter()
  const route = useRoute()

  try {
    // 1. 保存当前路由的完整配置
    // 注意：这里需要使用路由的原始配置，而不是当前匹配的路由对象
    // 我们需要从router.getRoutes()中找到匹配的路由配置
    const currentRouteConfig = router.getRoutes().find((r) => r.path === route.path)

    if (!currentRouteConfig || !currentRouteConfig.name) {
      console.error('无法找到当前路由配置或路由没有名称')
      return
    }

    // 2. 移除当前路由
    router.removeRoute(currentRouteConfig.name)

    // 3. 重新添加路由
    // 创建一个新的路由配置对象，确保完全复制原始配置
    const newRouteConfig = {
      ...currentRouteConfig,
      // 深拷贝meta对象，避免引用相同对象
      meta: { ...currentRouteConfig.meta }
    }

    router.addRoute(newRouteConfig)

    // 4. 使用replace方法跳转，强制重新渲染
    // 添加时间戳参数确保路由变化被检测到
    router.replace({
      path: route.path,
      query: {
        ...route.query,
        t: Date.now() // 添加时间戳作为唯一标识
      }
    })

    console.log('路由已重新加载，页面将重绘')
  } catch (error) {
    console.error('重绘页面时出错:', error)
  }
}

const reloadPage = () => {
  // 跳转到指定页面
  hardReload()
}
const jump = () => {
  // window.location.replace('/bigScreen')
  // window.location.replace(route.fullPath)
  // 打印当前路由路径
  console.log('当前路由路径:', route)
  console.log('当前路由路径:', route.fullPath)
  console.log('当前路由路径:', router)

  const timestamp = Date.now()
  window.location.replace('/bigScreen?t=' + timestamp)

  // 添加时间戳参数确保路由变化被检测到

  // router.push({ name: 'user', params: { username: 'eduardo' } })

  // router
  //   .replace({
  //     path: route.fullPath,
  //     query: {
  //       ...router.currentRoute.value?.query,
  //       t: timestamp
  //     }
  //   })
  //   .catch((error) => {
  //     if (!error.message.includes('NavigationDuplicated')) {
  //       console.error('路由替换失败:', error)
  //       // 如果路由替换失败，尝试使用window.location.reload()
  //       window.location.reload()
  //     }
  //   })

  // 跳转到指定页面
  // router.push('/')
  // router.push('/bigScreen')
}

// 定义一个响应式变量来存储当前时间
const currentTime = ref(getCurrentDateTime())

function getCurrentDateTime() {
  const now = new Date()
  const year = now.getFullYear()
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  const seconds = now.getSeconds().toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

let timer = null

// 窗口大小改变处理
const handleResize = () => {
  // 重新绘制窗口
}

// 在组件挂载时启动定时器
onMounted(() => {
  // 添加窗口大小改变事件监听器
  window.addEventListener('resize', handleResize)

  timer = setInterval(() => {
    currentTime.value = getCurrentDateTime()
  }, 1000)
})

// 在组件卸载时清除所有定时器
onBeforeUnmount(() => {
  // 清除时间更新定时器
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  // 清除 opacity 动画定时器
  if (opacityAnimationTimer) {
    clearInterval(opacityAnimationTimer)
    opacityAnimationTimer = null
  }
})
</script>

<template>
  <RouterView :key="$route.fullPath" />
  <div class="app-background-wrapper">
    <div class="app-background"></div>

    <el-row :gutter="10" class="page-header">
      <el-col>
        <dv-border-box-11 title="视频监控主控屏">
          <div class="name">创作人：Yunzhh.com</div>
          <div class="time">{{ currentTime }}</div>
          <!-- 添加切换背景的按钮 -->
          <div class="toggle-bg-btn">
            <button text @click="toggleBackground" class="bg-toggle-button">
              {{ getButtonText() }}
            </button>
            <!-- <router-link to="/bigScreen?t={{ currentTime }}">Go to Foo</router-link> -->
          </div>
          <!-- <el-button-group style="position: absolute; top: 50%; right: 120px">
            <el-button text icon="el-icon-arrow-left" @click="reloadPage">重绘</el-button>
            <el-button text icon="el-icon-arrow-right" @click="jump">跳转</el-button>
          </el-button-group> -->
        </dv-border-box-11>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="main-body">
      <el-col :span="6">
        <el-row class="el-row-v-3">
          <el-col :span="24">
            <dv-border-box-1>
              <div class="chart-container">
                <AntV_L_1 />
              </div>
              <!-- <LeftOne /> -->
              <!-- <AntV_L_1 /> -->
            </dv-border-box-1>
          </el-col>
        </el-row>

        <el-row class="el-row-v-3s">
          <el-col :span="24">
            <dv-border-box-8>
              <div class="chart-container">
                <LeftTwo />
              </div>
              <!-- <LeftTwo /> -->
              <!-- <AntV_L_1 /> -->
            </dv-border-box-8>
          </el-col>
        </el-row>

        <el-row class="el-row-v-3">
          <el-col :span="24">
            <dv-border-box-1>
              <div class="chart-container">
                <LeftThree />
              </div>
              <!-- <LeftThree /> -->
              <!-- <AntV_L_1 /> -->
            </dv-border-box-1>
          </el-col>
        </el-row>
      </el-col>

      <!-- 中间列 -->
      <el-col :span="12">
        <el-row class="el-row-v-3">
          <el-col :span="24">
            <dv-border-box-8 class="center-top">
              <div class="center-top-item">
                <div class="center-top-item-span">
                  <span>当前需求数量</span>
                  <CenterOne />
                </div>

                <div class="line"></div>

                <div class="center-top-item-span">
                  <span>预计需求数量</span>
                  <CenterOne />
                </div>
              </div>
            </dv-border-box-8>
          </el-col>
        </el-row>

        <el-row class="el-row-v-6">
          <el-col :span="24">
            <dv-border-box-1>
              <!-- <CenterTwo /> -->
              <div class="chart-container">
                <CenterTwo />
              </div>
            </dv-border-box-1>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧列 -->
      <el-col :span="6">
        <el-row class="el-row-v-3">
          <el-col :span="24">
            <dv-border-box-1>
              <div class="chart-container">
                <RightOne />
                <!-- <AntV_L_1 /> -->
              </div>
            </dv-border-box-1>
          </el-col>
        </el-row>

        <el-row class="el-row-v-3">
          <el-col :span="24">
            <dv-border-box-1>
              <div class="chart-container">
                <RightTwo />
                <!-- <AntV_L_1 /> -->
              </div>
              <!-- <RightTwo /> -->
              <!-- <AntV_L_1 /> -->
            </dv-border-box-1>
          </el-col>
        </el-row>

        <el-row class="el-row-v-3s">
          <el-col :span="24">
            <dv-border-box-8 reverse="true">
              <div class="chart-container">
                <RightThree />
              </div>
            </dv-border-box-8>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="less">
.app-background-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.app-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-image: v-bind(getCurrentBackgroundImage());
    opacity: v-bind(backgroundOpacity);
  }
}

.page-header {
  height: 12vh;
  background-color: rgba(0, 0, 0, 0.7);
  position: relative;
  z-index: 1;

  .name {
    position: absolute;
    left: 100px;
    top: 52%;
    // transform: translateY(-50%);
    color: #00f2ff;
    text-shadow:
      0 0 3px #00f2ff,
      0 0 40px #00f2ff;
    font-weight: 700;
    font-size: 0.9rem;
  }

  .time {
    position: absolute;
    right: 150px;
    top: 52%;
    // transform: translateY(-50%);
    font-weight: 700;
    color: #00f2ff;
    text-shadow:
      0 0 5px #00f2ff,
      0 0 40px #00f2ff;
    font-size: 0.9rem;
  }

  .toggle-bg-btn {
    position: absolute;
    right: 50px;
    top: 50%;
    // transform: translateY(-50%);

    .bg-toggle-button {
      // padding: 5px 15px;
      background-color: rgba(0, 242, 255, 0);
      color: #00f2ff;
      border: 0px solid #00f2ff;
      // border-radius: 4px;
      font-weight: bold;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background-color: rgba(0, 242, 255, 0.4);
        box-shadow: 0 0 10px #00f2ff;
      }
    }
  }
}

.main-body {
  width: calc(100% - 10px);
  height: calc(88vh - 40px);
  // padding: 10px;
  position: relative;
  z-index: 1;
}

.el-row-v-3,
.el-row-v-3s {
  margin: 10px;
  padding: 5px;
  width: calc(100% - 5px);
  height: calc(100% / 3);
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 8px;

  .r3 {
    // padding: 30px;
    // overflow: hidden;
    // padding-top: 20px;
    // height: 100%;
    // background-color: rgba(62, 36, 210, 0.7);
  }
}
.el-row-v-3s {
  // margin-bottom: 0px;
  // padding-bottom: 0px;
}

.el-row-v-6 {
  margin: 10px;
  padding: 5px;
  width: calc(100% - 5px);
  height: calc(100% * 2 / 3 + 10px);
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 8px;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  background-color: rgba(98, 200, 34, 0.5);
}

.center-top {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: inset 0 0 15px rgba(0, 98, 255, 0.2);
  box-sizing: border-box;

  .center-top-item {
    display: flex;
    width: 100%;
    height: 100%;
    justify-content: space-around;
    align-items: center;

    .line {
      display: flex;
      width: 5px;
      height: 30%;
      background-color: #3be1c4;
    }

    .center-top-item-span {
      display: flex;
      height: 100%;
      align-items: center;
      justify-content: center;
      flex-wrap: wrap;
      flex-direction: column;

      span {
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
        font-weight: 700;
        color: #00f2ff;
        text-shadow: 0 0 5px #00f2ff;
      }
    }
  }
}

.chart-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中（可选） */
  min-height: 0px; /* 父级要有高度，否则看不出效果 */
  height: 96%;
  padding: 20px 20px 0px;
}
</style>
